package com.ruoyi.plus.api.appLogin;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.api.ApiResult;
import com.ruoyi.common.core.api.BaseApi;
import com.ruoyi.common.core.api.version.ApiVersion;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.framework.web.service.UserDetailsServiceImpl;
import com.ruoyi.plus.api.appLogin.po.AppLoginPhonePo;
import com.ruoyi.plus.api.appLogin.vo.AppLoginVo;
import com.ruoyi.plus.utils.sms.ISmsService;
import com.ruoyi.plus.utils.sms.api.SmsApi;
import com.ruoyi.plus.utils.sms.domain.CheckCodeModel;
import com.ruoyi.plus.web.service.SysLoginServicePlus;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * app端第三方登录接口
 *
 * @author likun
 */
@Slf4j
@Api(tags = "AppLoginApi-app登录")
@ApiVersion
@RestController
@RequestMapping("/app/api/plus/appLoginApi")
public class AppLoginApi extends BaseApi {

    @Autowired
    UserDetailsServiceImpl userDetailsService;
    @Autowired
    private ISmsService smsService;
    @Autowired
    private SysLoginServicePlus loginService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private TokenService tokenService;


    /**
     * 用户存在则登录,用户不存在则创建用户并登录.
     *
     * @param appLoginPo 登录信息
     * @return 结果
     */
    @ApiOperation("loginByPhone-App手机号验证码注册登录")
    @PostMapping("/loginByPhone")
    @ResponseBody
    public ApiResult<AppLoginVo> loginByPhone(@Validated @RequestBody AppLoginPhonePo appLoginPo) {
        String phone = appLoginPo.getPhone();
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(appLoginPo.getCode())) {
            return new ApiResult<AppLoginVo>().setCode(-1).setMsg("手机号或验证码未传值!");
        }
        phone = phone.trim();
        if (!SmsApi.validatePhone(phone)) {
            return new ApiResult<AppLoginVo>().setCode(-1).setMsg("手机号格式不正确!");
        }
        CheckCodeModel checkCodeModel = smsService.checkCode(phone, appLoginPo.getCode());
        if (!checkCodeModel.isCheckResult()) {
            return new ApiResult<AppLoginVo>().setCode(-1).setMsg(checkCodeModel.getCheckMsg());
        }

        LoginUser loginUser = loginService.loginByPhone(phone);
        SysUser sysUser;
        if (loginUser == null) {
            sysUser = new SysUser();
            sysUser.setUserName(phone);
            sysUser.setPhonenumber(phone);
            sysUser.setNickName(phone);
            String password = configService.selectConfigByKey("sys.user.passwordInit");
            sysUser.setPassword(SecurityUtils.encryptPassword(password));
            //用户不存在,新增用户
            sysUserService.insertUser(sysUser);
            //重新加载用户,获取tenantId等信息.
            sysUser = sysUserService.selectUserById(sysUser.getUserId());
            loginUser = (LoginUser) userDetailsService.createLoginUser(sysUser);
        } else {
            sysUser = loginUser.getUser();
            if (sysUser != null && UserConstants.USER_DISABLE.equals(sysUser.getStatus())) {
                return new ApiResult<AppLoginVo>().setData(null).setMsg("该用户账号已被停用！").setCode(-1);
            }
        }

        AppLoginVo result = new AppLoginVo();
        result.setUserId(sysUser.getUserId())
                .setUserName(sysUser.getUserName())
                .setNickName(sysUser.getNickName())
                .setPhone(sysUser.getPhonenumber())
                .setSex(sysUser.getSex())
                .setAvatar(sysUser.getAvatar())
                //获取令牌
                .setToken(tokenService.createToken(loginUser))
                //获取权限列表
                .setPermissions(loginUser.getPermissions());
        SysDept dept = sysUser.getDept();
        if (dept != null) {
            result.setDeptId(dept.getDeptId()).setDeptName(dept.getDeptName());
        }
        return new ApiResult<AppLoginVo>().setMsg("登录成功!").setData(result);
    }

}
